package com.example.administrator.demoa;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int SHOW_CONTENT = 1001;
    private EditText edtPhone;
    private TextView txtResult;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtPhone = findViewById(R.id.edtPhone);
        txtResult = findViewById(R.id.txt_result);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what == SHOW_CONTENT){
                    String obj = (String) msg.obj;
                    txtResult.setText(obj);
                }
                return false;
            }
        });

        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //android.os.NetworkOnMainThreadException
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String phone = edtPhone.getText().toString();
                        useHttpGet(phone);
                    }
                }).start();
            }
        });

        findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String phone = edtPhone.getText().toString();
                        useHttpPost(phone);
                    }
                }).start();
            }
        });
    }

    private void useHttpPost(String phone) {
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        HttpClient httpClient = new DefaultHttpClient();
        List<NameValuePair> postParam = new ArrayList<>();
        postParam.add(new BasicNameValuePair("mobileCode",phone));
        postParam.add(new BasicNameValuePair("userID", ""));
        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(postParam));
            HttpResponse httpResponse = httpClient.execute(httpPost);

            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line != null){
                buffer.append(line);
                line = bufferedReader.readLine();
            }
            Log.e(TAG, "响应文本信息："+ buffer );

            Message message = Message.obtain();//创建一个对象，相当于new Message()
            message.what = SHOW_CONTENT;
            message.obj = buffer.toString();
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void useHttpGet(String phone) {
        //获得国内手机号码归属地省份、地区和手机卡类型信息
        //通过百度webxml
        String baseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        String url = baseUrl.concat("?mobileCode=").concat(phone).concat("&userID=");
        //由于HttpClient在Android6.0及以下版本使用
        //需要在build中配置useLibrary 'org.apache.http.legacy'
        //使用系统默认的HttpClient即可
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        try {
            //客户端执行get请求
            HttpResponse httpResponse = httpClient.execute(httpGet);
            //获取状态行
            int code = httpResponse.getStatusLine().getStatusCode();
            ProtocolVersion protocolVersion = httpResponse.getStatusLine().getProtocolVersion();
            String protocol = protocolVersion.getProtocol();
            Log.e(TAG, "code = "+ code + " version = " + protocol + protocolVersion.getMajor()+
                    "." + protocolVersion.getMinor());

            //通过输入流来读取文件,获取响应文本
            //IO针对的是程序
            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line != null){
                buffer.append(line);
                line = bufferedReader.readLine();
            }
            Log.e(TAG, "响应文本信息："+ buffer );

            //由于子线程不能修改UI界面，故不可用txtResult.setText(buffer);
            //需要通过handler来发消息机制提醒主线程修改UI
            Message message = Message.obtain();//创建一个对象，相当于new Message()
            message.what = SHOW_CONTENT;
            message.obj = buffer.toString();
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
